import { prisma } from '@/utils/backend/db'
import { HttpStatus } from '@/utils/httpStatus'
import { NextResponse } from 'next/server'

export const PATCH = async (req: Request, { params }: { params: { id: string } }) => {
  try {
    const { oldPassword, newPassword } = await req.json()
    const id = parseInt(params.id)

    // 验证旧密码
    const user = await prisma.user.findUnique({
      where: { id }
    })

    if (!user || user.password !== oldPassword) {
      return NextResponse.json(
        {
          success: false,
          message: '当前密码错误'
        },
        { status: 200 }
      )
    }

    // 更新密码
    await prisma.user.update({
      where: { id },
      data: { password: newPassword }
    })

    return NextResponse.json({
      success: true,
      message: '密码修改成功'
    })
  } catch (error) {
    console.error('Update password failed:', error)
    return NextResponse.json(
      {
        success: false,
        message: '服务器错误'
      },
      { status: HttpStatus.INTERNAL_SERVER_ERROR }
    )
  }
}
